<template>
  <div
    v-show="mapModuleIndex === 1||mapModuleIndex === 2"
    id="scene"
    :class="mapModuleIndex===2?'sceneright':'scenefull'">
    <scene-coordinate ref="coordinate"/>
    <scene-route-fly v-show="sceneTool&&sceneTool.showFlyRouteModule"/>
    <div id="vertical-slider"/>
    <div id="horizontal-slider"/>
  </div>
</template>
<script>
  import { SceneUtil } from '../../assets/js/scene/SceneUtil'
  import { mapState } from 'vuex'
  import SceneCoordinate from '@/pages/yzt/components/sceneCoordinate'
  import { SceneTool } from '../../pages/yzt/components/SceneTool'
  import sceneRouteFly from '../../pages/yzt/components/sceneRouteFly'

  export default {
    name: 'Scene',
    components: { SceneCoordinate, sceneRouteFly },
    data() {
      return {
        loadScene: false, // 判断是否是第一次启动
        relateScene: false, // 二三维联动串联避让
        scenePosition: undefined
      }
    },
    computed: {
      ...mapState({
        // 地图模块控件
        mapModuleIndex(state) {
          return state.eswyzt.mapModuleIndex
        },
        // 地图范围参数
        extentChangeSourceMap(state) {
          return state.eswyzt.extentChangeSourceMap
        },

        // 底图图层
        baseLayer_3D(state) {
          return state.user.baseLayer_3D
        },

        // 三维高程图层
        eleLayer_3D(state) {
          return state.user.eleLayer_3D
        },
        // 三维工具类
        sceneTool(state) {
          return state.eswyzt.sceneTool
        }
      })
    },
    watch: {
      mapModuleIndex(val) {
        if (!this.loadScene) {
          this.loadScene = true
          let viewer
          // if (this.eleLayer_3D) {
          //   if (this.eleLayer_3D.length > 0) {
          //     viewer = new Cesium.Viewer('scene', {
          //       terrainProvider: new Cesium.CesiumTerrainProvider({
          //         url: this.eleLayer_3D[0].url,
          //         isSct: true,
          //       }),
          //       selectionIndicator: false,
          //       infoBox: false,
          //       navigation: false
          //     })
          //   } else {
          //     viewer = new Cesium.Viewer('scene', {
          //       selectionIndicator: false,
          //       infoBox: false
          //     })
          //   }
          // } else {
            viewer = new Cesium.Viewer('scene', {
              selectionIndicator: false,
              infoBox: false
            })
         // }

           viewer.scene.globe.loadingMode = Cesium.LoadingPriorityMode.Root_Priority;
           viewer.scene.globe.tileCacheSize = 5000;

          //SceneUtil.tdtImageLayerAdd(viewer);
          // this.baseLayer_3D.forEach(baseLayer => {
          //   const sceneParam = SceneUtil.parseLayerUrlParam(baseLayer.url)
          //   const sceneUrl = SceneUtil.parseLayerUrl(baseLayer.url)
          //   if (sceneParam && sceneUrl) {
          //     SceneUtil.sceneLayerAdd(viewer, sceneUrl, sceneParam.name, sceneParam.sceneType)
          //   }
          // })

          // 去除超图logo
          const cesiumWidget = document.getElementsByClassName('cesium-widget-credits')
          for (let i = 0; i < cesiumWidget.length; i++) {
            cesiumWidget[i].style.display = 'none'
          }

          this.$emit('onInitSceneViewer', viewer)
          this.$store.commit('eswyzt/setSceneViewer', viewer)
          this.$store.commit('eswyzt/setSceneTool', new SceneTool(viewer))
          // 二三维联动相关
          viewer.camera.changed.addEventListener((percentage) => {
            if (this.relateScene) {
              return
            }

            if (this.$store.state.eswyzt.sceneViewer.camera.pitch > -0.2) { return }

            const source = {
              type: '3d',
              center: this.getCenterPosition(),
              bounds: this.getCurrentExtent()
            }
            this.$store.commit('eswyzt/setExtentChangeSourceScene', source)
          })
          var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
          handler.setInputAction((click) => {
            this.relateScene = false
          }, Cesium.ScreenSpaceEventType.LEFT_UP)
          handler.setInputAction((click) => {
            this.relateScene = false
          }, Cesium.ScreenSpaceEventType.MIDDLE_UP)
          handler.setInputAction((click) => {
            this.relateScene = false
          }, Cesium.ScreenSpaceEventType.RIGHT_UP)
          handler.setInputAction((click) => {
            this.relateScene = false
          }, Cesium.ScreenSpaceEventType.WHEEL)

          viewer.scene.postRender.addEventListener(() => {
            // 每一帧都去计算气泡的正确位置
            if (this.scenePosition) {
              var canvasHeight = viewer.scene.canvas.height
              var windowPosition = new Cesium.Cartesian2()
              Cesium.SceneTransforms.wgs84ToWindowCoordinates(
                viewer.scene,
                this.scenePosition,
                windowPosition
              )
              const bottom = canvasHeight - windowPosition.y + 5 + 'px'
              const left = windowPosition.x - 140 + 'px'
              this.$emit('onPopuPosition', bottom, left)
            }

            // 导航罗盘指示代码
            const heading = viewer.scene.camera.heading
            const x = Cesium.Math.toDegrees(heading)
            const degrees = 'rotate(' + (-x - 45) + 'deg)'
            // document.getElementsByClassName('el-icon-position')[0].style.transform = degrees
          })

          handler.setInputAction((e) => {
            var position = viewer.scene.pickPosition(e.position)
            if (!position) {
              position = Cesium.Cartesian3.fromDegrees(0, 0, 0)
            }
            var selectLayer = viewer.scene.layers.getSelectedLayer()
            if (selectLayer !== undefined) {
              this.scenePosition = position // 气泡相关 2/4
              this.$emit('onSelectedLayer', selectLayer)
            }
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

          this.$refs.coordinate.initialControls(viewer)
        }
      },

      /**
       * 二维联动三维跟随
       */
      extentChangeSourceMap(val) {
        if (val === null) {
          return
        }
        if (this.$store.state.eswyzt.sceneViewer === null) {
          return
        }
        if (val.type === '2d') {
          this.relateScene = true
          this.$store.state.eswyzt.sceneViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(val.extent.x, val.extent.y, val.extent.h), // 设置位置
            orientation: {
              heading: Cesium.Math.toRadians(0.0), // 方向
              pitch: Cesium.Math.toRadians(-90.0), // 倾斜角度
              roll: 0
            }
          })
        }
      }
    },
    mounted() {
    },
    beforeDestroy() {
      this.loadScene = false
      this.relatedAddress = false
    },
    methods: {
      /**
       * 获取相机高度
       * @returns {*}
       */
      getHeight() {
        if (this.$store.state.eswyzt.sceneViewer) {
          var scene = this.$store.state.eswyzt.sceneViewer.scene
          var ellipsoid = scene.globe.ellipsoid
          var height = ellipsoid.cartesianToCartographic(this.$store.state.eswyzt.sceneViewer.camera.position).height
          return height
        }
      },
      /**
       * 获取中心点坐标
       * @returns {{lon: number, lat: number, height: *}}
       */
      getCenterPosition() {
        const result = this.$store.state.eswyzt.sceneViewer.camera.pickEllipsoid(
          new Cesium.Cartesian2(this.$store.state.eswyzt.sceneViewer.canvas.clientWidth / 2,
        this.$store.state.eswyzt.sceneViewer.canvas.clientHeight / 2))
        const curPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(result)
        const lon = curPosition.longitude * 180 / Math.PI
        const lat = curPosition.latitude * 180 / Math.PI
        const height = this.getHeight()
        return {
          lon: lon,
          lat: lat,
          height: height
        }
      },
      /**
       * 获取当前场景范围
       */
      getCurrentExtent() {
        // 范围对象
        var extent = {}
        // 得到当前三维场景
        var scene = this.$store.state.eswyzt.sceneViewer.scene
        // 得到当前三维场景的椭球体
        var ellipsoid = scene.globe.ellipsoid
        var canvas = scene.canvas
        // canvas左上角
        var car3_lt = this.$store.state.eswyzt.sceneViewer.camera.pickEllipsoid(new Cesium.Cartesian2(0, 0), ellipsoid)
        // canvas右下角
        var car3_rb = this.$store.state.eswyzt.sceneViewer.camera.pickEllipsoid(new Cesium.Cartesian2(canvas.width, canvas.height), ellipsoid)
        // 当canvas左上角和右下角全部在椭球体上
        if (car3_lt && car3_rb) {
          var carto_lt = ellipsoid.cartesianToCartographic(car3_lt)
          var carto_rb = ellipsoid.cartesianToCartographic(car3_rb)
          extent.xmin = Cesium.Math.toDegrees(carto_lt.longitude)
          extent.ymax = Cesium.Math.toDegrees(carto_lt.latitude)
          extent.xmax = Cesium.Math.toDegrees(carto_rb.longitude)
          extent.ymin = Cesium.Math.toDegrees(carto_rb.latitude)
        }
        // 当canvas左上角不在但右下角在椭球体上
        else if (!car3_lt && car3_rb) {
          var car3_lt2 = null
          var yIndex = 0
          do {
            // 这里每次10像素递加，一是10像素相差不大，二是为了提高程序运行效率
            yIndex <= canvas.height ? yIndex += 10 : canvas.height
            car3_lt2 = this.$store.state.eswyzt.sceneViewer.camera.pickEllipsoid(new Cesium.Cartesian2(0, yIndex), ellipsoid)
          } while (!car3_lt2)
          var carto_lt2 = ellipsoid.cartesianToCartographic(car3_lt2)
          var carto_rb2 = ellipsoid.cartesianToCartographic(car3_rb)
          extent.xmin = Cesium.Math.toDegrees(carto_lt2.longitude)
          extent.ymax = Cesium.Math.toDegrees(carto_lt2.latitude)
          extent.xmax = Cesium.Math.toDegrees(carto_rb2.longitude)
          extent.ymin = Cesium.Math.toDegrees(carto_rb2.latitude)
        }
        // 获取高度
        extent.height = Math.ceil(this.$store.state.eswyzt.sceneViewer.camera.positionCartographic.height)
        return extent
      }
    }
  }
</script>

<style>
  #scene {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    position: absolute;
  }

  .sceneright {
    width: 50% !important;
    left: 50%;
  }

  .scenefull {
    width: 100% !important;
    left: 0;
  }

  #vertical-slider {
    position: absolute;
    left: 50%;
    top: 0px;
    background-color: #D3D3D3;
    width: 5px;
    height: 100%;
    z-index: 9999;
    display: none;
    cursor: ew-resize;
  }

  #horizontal-slider {
    position: absolute;
    left: 0;
    top: 50%;
    background-color: #D3D3D3;
    width: 100%;
    height: 5px;
    z-index: 9999;
    display: none;
    cursor: ns-resize;
  }

</style>

